package main

import (
	"fmt"
	"os"
	"strings"

	"example.com/dcache/client"
	"github.com/peterh/liner"
)

func main() {
	//Get server address from cmd line

	if len(os.Args) > 2 {
		panic("Should only provide 1 address")
	}
	addr := os.Args[1]

	//Contact with server
	line := liner.NewLiner()
	defer line.Close()
	line.SetCtrlCAborts(true)

	commandSet := map[string]bool{}
	for _, cmd := range client.CommandList {
		commandSet[strings.ToLower(cmd[0])] = true
	}

	prompt := addr + ">"
	for {
		cmd, err := line.Prompt(prompt)
		if err != nil {
			fmt.Println(err)
			break
		}

		cmd = strings.TrimSpace(cmd)
		if len(cmd) == 0 {
			continue
		}

		lowerCmd := strings.ToLower(cmd)
		c := strings.Split(lowerCmd, " ")

		if lowerCmd == "help" {
			client.PrintCmdHelp()
			continue
		}

		if lowerCmd == "quit" {
			break
		}

		if c[0] == "help" && len(c) == 2 {
			helpCmd := c[1]
			if !commandSet[helpCmd] {
				fmt.Println("Command not found")
				continue
			}

			for _, cmd := range client.CommandList {
				if helpCmd == strings.ToLower(cmd[0]) {
					fmt.Println()
					fmt.Println(" --usage: " + helpCmd + " " + cmd[1])
					fmt.Println(" --group: " + cmd[2] + "\n")
				}
			}
		}

		command, args := client.ParseCommandLine(lowerCmd)
		//fmt.Println(command, args)

		node, result, errString := client.HandleCmd(addr, command, args)
		if errString != "" {
			fmt.Println(errString)
			continue
		}

		if command != "delgroup" {
			fmt.Println("[hit on] > " + node)
		}

		fmt.Println(result)
	}
}
